package com.simple.card.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class IAuth {

    public boolean checkSignPass(String sign, String timestamp,StringRedisTemplate redisTemplate) {

        String str = AesUtil.decryptData(sign);
        if(StringUtils.isEmpty(str)) {
            return false;
        }
        if((new Date().getTime()/1000 - Long.valueOf(timestamp)/1000) > 300) {
            log.error("[sign校验]请求超时");
            return false;
        }
        //同一个sign只能请求一次
        if("1".equals(redisTemplate.opsForValue().get(sign))) {
            return false;
        }
        return true;
    }

    public static String setAppLoginToken(String phone) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return getMD5(uuid + phone);
    }

    //MD5加密
    public static String getMD5(String message) {
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageByte = message.getBytes("UTF-8");
            byte[] md5Byte = md.digest(messageByte);
            md5 = bytesToHex(md5Byte);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return md5;
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
            if(num < 0) {
                num += 256;
            }
            if(num < 16){
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }
}